import { useUserStoreWithOut } from "@/store/modules/user";
import { LayoutMenu } from "@/layouts/hooks/getLayoutMenu";

// 禁止事件响应
const stopEvent = (e) => {
  e.stopImmediatePropagation();
};

export default function (el, binding) {
  const permissionVal = binding.value;
  const permissionType = binding.arg ?? "visible";
  if (permissionVal) {
    const layoutMenu = new LayoutMenu();
    const { pathname, search } = window.location;
    const code = layoutMenu.getPathByCode(pathname + search);
    const valueWithCode = `${code ? code + "_" : ""}${permissionVal}`;
    const userStore = useUserStoreWithOut();
    const permissionCodeMap: string[] = userStore.getPermissionMap || [];
    if (permissionCodeMap && !permissionCodeMap.some((item) => {
      let permissionCode = item;
      if (code && !item.startsWith(code)) {
        permissionCode = `${code}_${permissionCode}`
      }
      return permissionCode.includes(valueWithCode)
    })) {
      switch (permissionType) {
        case "visible":
          //没有权限隐藏元素
          el.style.display = "none";
          break;
        case "operable":
          //没有权限禁用元素
          const _class = el.classList[0] + "-disabled";
          el.classList.add(_class);
          el.classList.add(`permission-disabled-style`);
          el.setAttribute("disabled", true);
          // 禁止滑动条响应事件
          if (_class.includes("slider")) {
            el.addEventListener("mousedown", stopEvent, true);
          }
          // 禁止选择器响应事件
          if (_class.includes("picker")) {
            // 普通时间选择器用的mouseup
            el.addEventListener("mouseup", stopEvent, true);
            // 时间区间用的click
            el.addEventListener("click", stopEvent, true);
          }

          break;
      }
    }
  }
}
